<script setup>
import { ref, onMounted, nextTick } from 'vue'
import useTableView from '@/hooks/use-table-view'
import DialogRole from '@/views/system/role/components/DialogRole.vue'
import useDelPop from '@/hooks/use-del-popover'
import DialogRolePermission from '@/views/system/role/components/DialogRolePermission.vue'
import { delRoleMockApi, pageRoleMockApi } from '@/api/mock-js/system/role-api'

// 角色管理界面-这里主要分配权限以及增加角色等功能
defineOptions({
  name: 'Role'
})

const queryInfo = ref({ params: {} })
const { tableData, renderTable, loading, total, del, dialogRef, showDialog, visibleDialog } = useTableView(queryInfo)
// 删除 hooks
const { delData, visibleDelPop, tempRef, showDelPop } = useDelPop()

// 分配权限 弹窗
const dialogPermissionRef = ref()
const visiblePermissionDialog = ref(false)
const showSubDialog = (row) => {
  visiblePermissionDialog.value = true
  nextTick(() => {
    dialogPermissionRef.value.title = row.roleName
    dialogPermissionRef.value.formData.roleId = row.id
    dialogPermissionRef.value.initData?.()
  })
}

onMounted(async () => {
  await renderTable?.(pageRoleMockApi, 1)
})
</script>

<template>
  <TableView class="role" v-loading="loading" v-model="queryInfo.pageNum" v-model:pageSize="queryInfo.pageSize"
    :total="total" @reload-table="renderTable(pageRoleMockApi)">
    <template #header>
      <ViewSearchForm v-model="queryInfo" :tool-list="['keyword']" @on-search="renderTable(pageRoleMockApi)" />
    </template>
    <template #headerRight>
      <ElButton type="primary" @click="showDialog()">添加角色</ElButton>
    </template>
    <ElTable ref="tableRef" :data="tableData" style="width: 100%;" border stripe>
      <ElTableColumn type="index" label="ID" />
      <ElTableColumn prop="roleName" label="角色名" width="200" />
      <ElTableColumn prop="roleKey" label="角色键值" width="200" />
      <ElTableColumn prop="remarks" label="备注" min-width="200" />
      <ElTableColumn label="操作" width="220" #default="{ row }">
        <ElButton size="small" @click="e => showDelPop(e, row, `角色-${row.roleName}`)">删除</ElButton>
        <ElButton size="small" type="primary" plain @click="showSubDialog(row)">分配权限</ElButton>
        <ElButton size="small" type="primary" @click="showDialog(row, `-${row.roleName}`)">编辑</ElButton>
      </ElTableColumn>
    </ElTable>
    <!--  删除popover start -->
    <DeletePopover v-if="visibleDelPop" :temp-ref="tempRef" v-model:del-info="delData" v-model="visibleDelPop"
      @on-submit="del(delData.id, delRoleMockApi, pageRoleMockApi)" />
    <!--  删除popover end -->
    <!-- 添加、编辑 dialog -->
    <DialogRole ref="dialogRef" v-if="visibleDialog" v-model="visibleDialog" @on-close="renderTable(pageRoleMockApi)" />
    <!--  分配角色权限  -->
    <DialogRolePermission ref="dialogPermissionRef" v-if="visiblePermissionDialog" v-model="visiblePermissionDialog"
      @on-close="renderTable(pageRoleMockApi)" />
  </TableView>
</template>
